﻿using Entity;
using GL_CommonPrint.DataModels;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using static GL_CommonPrint.FilePath;
using static GL_CommonPrint.FrontReader;

using Color = System.Drawing.Color;

namespace GL_CommonPrint
{
    internal partial class ExcelGenerator
    {
        internal ReturnResult Create(string jsonStr, string excelPath)
        {
            // Excel数据文档对象
            var dataWb = JsonConvert.DeserializeObject<GL_WorkBook>(jsonStr);

            var workbook = new XSSFWorkbook();

            try
            {
                // 如果源文件路径为空，并且用户在模型中没有给Excel数据文档对象的文件名赋值，自动命名
                if (string.IsNullOrEmpty(excelPath) && string.IsNullOrEmpty(dataWb.fileName))
                {
                    dataWb.fileName = DateTime.Now.ToString("yyyy年MM月dd日_HH时mm分ss秒") + ".xlsx";
                }
                if (string.IsNullOrEmpty(excelPath))
                {
                    excelPath = getFullPath(GL_FileType.TemplateExcel, dataWb.fileName);
                }

                using (FileStream file = new FileStream(excelPath, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    workbook = new XSSFWorkbook(file);
                    file.Close();
                }

                foreach (var dataSheet in dataWb.sheets)
                {
                    // 如果没有表就创建一个
                    var sheet = workbook.GetSheet(dataSheet.name);
                    if (sheet is null)
                    {
                        sheet = workbook.CreateSheet(dataSheet.name);
                    }

                    foreach (var dataRow in dataSheet.rows)
                    {
                        // 获取cellStyle
                        var styles = new Dictionary<string, ICellStyle>();
                        foreach (var dataStyle in dataSheet.styles)
                        {
                            var style = workbook.CreateCellStyle();

                        }

                        var row = sheet.GetRow(dataRow.rowIndex - 1);
                        if (row is null)
                        {
                            row = sheet.CreateRow(dataRow.rowIndex - 1);
                            row.Height = dataRow.rowHeight;
                        }
                        foreach (var dataCell in dataRow.cells)
                        {
                            var cell = row.GetCell(dataCell.columnIndex - 1);
                            if (cell is null)
                            {
                                cell = row.CreateCell(dataCell.columnIndex - 1);
                            }

                            // 添加单元格样式
                            if (dataCell.styleName != null && styles.Keys.Contains(dataCell.styleName))
                            {
                                cell.CellStyle =
                                styles[dataCell.styleName];
                            }

                            if (!string.IsNullOrEmpty(dataCell.stringContent))
                            {
                                cell.SetCellType(CellType.String);
                                cell.SetCellValue(dataCell.stringContent);
                            }
                            else if (!string.IsNullOrEmpty(dataCell.numberContent))
                            {
                                cell.SetCellType(CellType.Numeric);
                                cell.SetCellValue(double.Parse(dataCell.numberContent));
                            }
                        }
                    }

                    foreach (var dataPhoto in dataSheet.photos)
                    {
                        if (dataPhoto.readableCode != null)
                        {
                            var readCode = dataPhoto.readableCode;

                            if (readCode.type == CodeType.CODE128)
                            {
                                BarcodeLib.Barcode b = new BarcodeLib.Barcode();
                                Image img = b.Encode(BarcodeLib.TYPE.CODE128, readCode.realContent, Color.Black, Color.White, 600, 120);

                                var memoryStream = new MemoryStream();
                                img.Save(memoryStream, ImageFormat.Png);

                                var barCodeIndex = workbook.AddPicture(memoryStream.ToArray(), PictureType.PNG);

                                ICreationHelper helper = workbook.GetCreationHelper();
                                IDrawing drawing = sheet.CreateDrawingPatriarch();

                                IClientAnchor anchor = helper.CreateClientAnchor();

                                //anchor.AnchorType = AnchorType.MoveDontResize;

                                anchor.Col1 = dataPhoto.beginColumn - 1;//0 index based column
                                anchor.Row1 = dataPhoto.beginRow - 1; //0 index based row
                                anchor.Col2 = dataPhoto.endColumn - 1;
                                anchor.Row2 = dataPhoto.endRow - 1;

                                IPicture picture = drawing.CreatePicture(anchor, barCodeIndex);
                                //picture.Resize();
                            }

                            for (int i = 0; i < sheet.LastRowNum; i++)
                            {
                                if (sheet.GetRow(i) == null)
                                {
                                    sheet.CreateRow(i);
                                }

                                var r = sheet.GetRow(i);

                                for (int j = 0; j < r.LastCellNum; j++)
                                {
                                    if (r.GetCell(j) == null)
                                    {
                                        r.CreateCell(j);
                                    }
                                }
                            }

                            if (readCode.type == CodeType.QRCode)
                            {
                                QRCodeGenerator qrGenerator = new QRCodeGenerator();
                                QRCodeData qrCodeData = qrGenerator.CreateQrCode(readCode.realContent, QRCodeGenerator.ECCLevel.Q);
                                QRCode qrCode = new QRCode(qrCodeData);
                                Bitmap qrCodeImage = qrCode.GetGraphic(20);

                                var memoryStream = new MemoryStream();
                                qrCodeImage.Save(memoryStream, ImageFormat.Png);

                                var barCodeIndex = workbook.AddPicture(memoryStream.ToArray(), PictureType.PNG);

                                ICreationHelper helper = workbook.GetCreationHelper();
                                IDrawing drawing = sheet.CreateDrawingPatriarch();

                                IClientAnchor anchor = helper.CreateClientAnchor();

                                //anchor.AnchorType = AnchorType.MoveDontResize;

                                anchor.Col1 = dataPhoto.beginColumn - 1;//0 index based column
                                anchor.Row1 = dataPhoto.beginRow - 1; //0 index based row
                                anchor.Col2 = dataPhoto.endColumn - 1;
                                anchor.Row2 = dataPhoto.endRow - 1;

                                IPicture picture = drawing.CreatePicture(anchor, barCodeIndex);
                            }
                        }
                    }
                }

                using (FileStream file = new FileStream(excelPath, FileMode.Truncate, FileAccess.Write))
                {
                    workbook.Write(file);

                    file.Close();
                    workbook.Close();
                }

                return new ReturnResult
                {
                    Result = true,
                    Message = "Json信息添加成功"
                };

            }
            catch (Exception ex)
            {
                workbook.Close();

                return new ReturnResult
                {
                    Result = false,
                    Message = ex.Message,
                    Data = ex.StackTrace
                };
            }
        }
    }

    internal partial class ExcelGenerator
    {

    }
}
